package com.grape.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.grape.pojo.User;
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("拦截器执行");
		
        HttpServletRequest req = (HttpServletRequest)request;   
        HttpServletResponse resp = (HttpServletResponse)response;   
        HttpSession session = req.getSession();  
        
        User user = (User)session.getAttribute("user");
        if (user == null) {
        	resp.setHeader("REDIRECT", "REDIRECT");// 告诉ajax这是重定向 设置到头  
        	resp.setHeader("CONTEXTPATH", "/time/user/login.html");// 重定向地址 设置到头
        	// 设置http的响应状态码 403,禁止访问,我会在ajax的js文件中获取这两份头信息跳转以解决ajax请求过拦截器重定向无效问题response.sendRedirect('url')
        	resp.setStatus(HttpServletResponse.SC_FORBIDDEN);  
			return;
		}
        
        chain.doFilter(request, response);   
	}

	@Override
	public void destroy() {
		
	}

}
